//
//  MYAttenZTViewController.m
//  app001
//
//  Created by xionghao on 15/10/8.
//  Copyright © 2015年 xionghao. All rights reserved.
//

#import "MYAttenZTViewController.h"
#import "BottomBar.h"
#import "Puser.h"
#import "NoItemView.h"
#import <MJRefresh.h>
#import "ZTAttenCar.h"
#import "AttenZTTableViewCell.h"
#import "UserInfoUpdateResde.h"
#import "MyZTTableViewController.h"

@interface MYAttenZTViewController ()<UITableViewDataSource,UITableViewDelegate,BottomBarBtnClickDelegate,UIAlertViewDelegate,BottombarDataSource>
{
    BOOL _isedting;
    BOOL _candelete;
}
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) NSMutableArray *datalist;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomBar *bottombar;
@property (nonatomic,weak) NoItemView *notitem;
@property (nonatomic,assign) BOOL isFromOther;
@end

@implementation MYAttenZTViewController

-(NSMutableArray *)datalist{
    if ( _datalist==nil) {
        _datalist=[NSMutableArray array];
    }
    return  _datalist;
}

+(instancetype)viewcontroller{
    MYAttenZTViewController *vc=[[MYAttenZTViewController alloc]init];
    return vc;
}
-(BottomBar *)bottombar{
    if (_bottombar==nil) {
        _bottombar=[[BottomBar alloc]initWithBtnTitleArray:@[@"取消关注"] WithDelegate:self :YES];
        _bottombar.ishwopost=NO;
        _bottombar.datasource=self;
        [_bottombar addInView:self.view];
    }
    return _bottombar;
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}


-(UITableView *)tableView{
    if (_tableView==nil) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, XHScreenheight) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=bgGarycolor;
        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
-(NSInteger)numberofBottobarcount:(BottomBar *)bottombar{
    return  self.datalist.count;
}
-(void)refreshing{
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"my_atten";
    params[@"num"]=Kpagesize;
    if (self.isFromOther) {
        params[@"user_id"]=self.user_id;
        params[@"type"]=self.user_type;
    }else{
    params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
    params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
    
    }
    [PostUitls Post:mynewzturl parameters:params success:^(id response) {
       [ZTAttenCar setupReplacedKeyFromPropertyName:^NSDictionary *{
          
           return @{
                    @"ID":@"id"
                    };
           
       }];
        NSDictionary *dict=response;
        [self.datalist removeAllObjects];
        NSArray *array=[ZTAttenCar objectArrayWithKeyValuesArray:dict[@"data"]];
        [self.datalist addObjectsFromArray:array];
        if (self.datalist.count>0) {
            [self.notitem hide];
        }else{
            [self.notitem show];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    
    } failure:^(NSError *error) {
        
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    }];
    
    
}
-(void)loadMoreData{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"my_atten";
    params[@"num"]=Kpagesize;
    
    params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
    params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
    

}


-(void)setupRight:(BOOL)iseidting{
    if (iseidting) {
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        [self.bottombar show];
        self.navigationItem.rightBarButtonItem=rightitem;
        
    }else{
        [self.bottombar hide];
        self.bottombar.allselected=NO;
        
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        
        self.navigationItem.rightBarButtonItem=rightitem;
    }
    
    
}

-(void)BottomBarAllclick:(BottomBar *)bottombar{
    for (ZTAttenCar *mode in self.datalist) {
        mode.ischecked=bottombar.allselected;
    }
    [self.tableView reloadData];
}

-(void)BottomBar:(BottomBar *)bottombar otherbtnClick:(NSInteger)index{
    if (index==0&&self.datalist.count>0) {
        [self showalert];
    }
}
-(void)showalert{
    UIAlertView *alret=[[UIAlertView alloc]initWithTitle:@"提示" message:@"确认取消关注么?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alret show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0)
        return;
    [self deleteZTAtten];
    
    
}
-(void)deleteZTAtten{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText=@"正在取消关注";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"can_atten";
    NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"type"]=@"person";
        params[@"user_id"]=self.user.user_id;
    }else{
        params[@"type"]=@"company";
        params[@"user_id"]=self.user.com_id;
    }
    
    NSMutableArray *IDarray=[NSMutableArray array];
    for (ZTAttenCar *mode in self.datalist) {
        if (mode.ischecked) {
            [IDarray addObject:mode.ID];
        }
    }
    params[@"att_id"]=[NSString DataTOjsonString:IDarray];
    
    [PostUitls Post:mynewzturl parameters:params success:^(id response) {
        UserInfoUpdateResde *resdmode=[UserInfoUpdateResde resdeWithDict:response];
        if ([resdmode.state integerValue]==400) {
            [self.tableView.header beginRefreshing];
            _candelete=NO;
            self.bottombar.btnenable=_candelete;
            self.bottombar.allselected=_candelete;
        }
        hud.labelText=resdmode.msg;
        hud.mode = MBProgressHUDModeText;
        [hud hide:YES afterDelay:1];
    } failure:^(NSError *error) {
        hud.labelText=@"网络错误";
        hud.mode = MBProgressHUDModeText;
    }];

}
-(void)rightclick{
    _isedting=!_isedting;
    [self setupRight:_isedting];
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NoItemView *noitem=[NoItemView viewWithType:STARTTYPE];
    
    [self.tableView addSubview:noitem];
    if (!self.user_id) {
        [self setupRight:NO];
    }else{
        self.isFromOther=YES;
    }
    _notitem=noitem;
    self.navigationItem.title=@"关注的展厅";
    self.tableView.rowHeight=81;
    self.tableView.backgroundColor=bgGarycolor;
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }
    [self setuptablview];
    // Do any additional setup after loading the view.
}



-(void)setuptablview{
    MJRefreshHeader *header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshing)];
    
    
    self.tableView.header=header;
    self.tableView.header.automaticallyChangeAlpha=YES;
    self.tableView.footer.hidden = YES;
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter  footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.stateLabel.font=[UIFont systemFontOfSize:10];
    footer.stateLabel.textColor=RGBACOLOR(125, 125, 125, 1);
    self.tableView.footer=footer;
      [self.tableView.header beginRefreshing];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.datalist.count>0) {
        tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    }else{
         tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    }
    return self.datalist.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZTAttenCar *mode=self.datalist[indexPath.row];
    
    AttenZTTableViewCell *cell=[AttenZTTableViewCell cellWithTableView:tableView];
    cell.isEditing=!_isedting;
    cell.mode=mode;
    return cell;    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}
     ];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbg"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTranslucent:YES];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZTAttenCar *mode=self.datalist[indexPath.row];
    if (_isedting) {
        mode.ischecked=!mode.ischecked;
        AttenZTTableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
        cell.editbtn.selected=!cell.editbtn.selected;
        for (ZTAttenCar *mode in self.datalist) {
            if (mode.ischecked) {
                _candelete=YES;
                break;
            }else{
                _candelete=NO;
            }
        }
        self.bottombar.btnenable=_candelete;
    }else{
        MyZTTableViewController *vc=[MyZTTableViewController viewcontroller];
        if ([mode.type integerValue]==0) {
            vc.user_id=mode.display_id;
        }else{
            vc.com_id=mode.display_id;
        }
        [self.navigationController pushViewController:vc animated:YES];
    
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
